import React, { useState } from 'react';
import {
  Card,
  CardMedia,
  CardContent,
  CardActions,
  Typography,
  IconButton,
  Chip,
  Avatar,
  Box,
  Tooltip,
} from '@mui/material';
import {
  Favorite,
  FavoriteBorder,
  Comment,
  Visibility,
  PlayArrow,
  Image as ImageIcon,
} from '@mui/icons-material';
import { ContentListItem, ContentType } from '../../../types';
import { ImageCarousel } from '../../../components';

interface ContentCardProps {
  content: ContentListItem;
  onLike: (contentId: number) => void;
  onComment: (contentId: number) => void;
  onView: (contentId: number) => void;
  loading?: boolean;
}

const ContentCard: React.FC<ContentCardProps> = ({
  content,
  onLike,
  onComment,
  onView,
  loading = false,
}) => {
  const [imageError, setImageError] = useState(false);

  const handleImageError = () => {
    setImageError(true);
  };

  const handleCardClick = () => {
    onView(content.id);
  };

  const handleLikeClick = (e: React.MouseEvent) => {
    e.stopPropagation();
    onLike(content.id);
  };

  const handleCommentClick = (e: React.MouseEvent) => {
    e.stopPropagation();
    onComment(content.id);
  };

  return (
    <Card
      sx={{
        height: '100%',
        display: 'flex',
        flexDirection: 'column',
        cursor: 'pointer',
        transition: 'transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out',
        '&:hover': {
          transform: 'translateY(-4px)',
          boxShadow: (theme) => theme.shadows[8],
        },
        opacity: loading ? 0.7 : 1,
      }}
      onClick={handleCardClick}
    >
      {/* 封面图片区域 */}
      <Box sx={{ position: 'relative', paddingTop: '75%' }}>
        {content.contentType === ContentType.IMAGE ? (
          // 图片内容：显示轮播图（封面 + 内容图片）
          (() => {
            const allImages: string[] = [];
            
            // 如果有封面，将封面作为第一张图片
            if (content.coverUrl) {
              allImages.push(content.coverUrl);
            }
            
            // 添加内容图片，但避免重复
            if (content.imageUrls && content.imageUrls.length > 0) {
              content.imageUrls.forEach(imageUrl => {
                if (!allImages.includes(imageUrl)) {
                  allImages.push(imageUrl);
                }
              });
            }
            
            return allImages.length > 0 ? (
              <Box
                sx={{
                  position: 'absolute',
                  top: 0,
                  left: 0,
                  width: '100%',
                  height: '100%',
                }}
              >
                <ImageCarousel
                  images={allImages}
                  alt={content.title}
                  height="100%"
                  width="100%"
                  objectFit="cover"
                  showIndicators={allImages.length > 1}
                  showNavigation={allImages.length > 1}
                  borderRadius={0}
                />
              </Box>
            ) : (
              <Box
                sx={{
                  position: 'absolute',
                  top: 0,
                  left: 0,
                  width: '100%',
                  height: '100%',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  backgroundColor: 'grey.200',
                  color: 'grey.500',
                }}
              >
                <ImageIcon sx={{ fontSize: 48 }} />
              </Box>
            );
          })()
        ) : (
          // 视频内容：显示封面或占位符
          !imageError && content.coverUrl ? (
            <CardMedia
              component="img"
              image={content.coverUrl}
              alt={content.title}
              onError={handleImageError}
              sx={{
                position: 'absolute',
                top: 0,
                left: 0,
                width: '100%',
                height: '100%',
                objectFit: 'cover',
              }}
            />
          ) : (
            <Box
              sx={{
                position: 'absolute',
                top: 0,
                left: 0,
                width: '100%',
                height: '100%',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                backgroundColor: 'grey.200',
                color: 'grey.500',
              }}
            >
              <PlayArrow sx={{ fontSize: 48 }} />
            </Box>
          )
        )}
        
        {/* 内容类型标识 */}
        <Chip
          icon={content.contentType === ContentType.VIDEO ? <PlayArrow /> : <ImageIcon />}
          label={content.contentType === ContentType.VIDEO ? '视频' : '图片'}
          size="small"
          sx={{
            position: 'absolute',
            top: 8,
            right: 8,
            backgroundColor: 'rgba(0, 0, 0, 0.7)',
            color: 'white',
            '& .MuiChip-icon': {
              color: 'white',
            },
          }}
        />

        {/* 发布状态标识 */}
        {!content.isPublished && (
          <Chip
            label="未发布"
            size="small"
            color="warning"
            sx={{
              position: 'absolute',
              top: 8,
              left: 8,
            }}
          />
        )}
      </Box>

      {/* 内容信息区域 */}
      <CardContent sx={{ flexGrow: 1, pb: 1 }}>
        <Typography
          variant="h6"
          component="h2"
          gutterBottom
          sx={{
            fontWeight: 600,
            fontSize: '1rem',
            lineHeight: 1.3,
            display: '-webkit-box',
            WebkitLineClamp: 2,
            WebkitBoxOrient: 'vertical',
            overflow: 'hidden',
            minHeight: '2.6em',
          }}
        >
          {content.title}
        </Typography>

        <Typography
          variant="body2"
          color="text.secondary"
          sx={{ fontSize: '0.875rem' }}
        >
          {new Date(content.createdAt).toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: 'short',
            day: 'numeric',
          })}
        </Typography>
      </CardContent>

      {/* 交互按钮区域 */}
      <CardActions
        sx={{
          justifyContent: 'space-between',
          px: 2,
          py: 1,
        }}
      >
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <Tooltip title={content.isLiked ? '取消点赞' : '点赞'}>
            <IconButton
              size="small"
              onClick={handleLikeClick}
              disabled={loading}
              sx={{
                color: content.isLiked ? 'error.main' : 'text.secondary',
                '&:hover': {
                  color: 'error.main',
                  backgroundColor: 'error.50',
                },
              }}
            >
              {content.isLiked ? <Favorite /> : <FavoriteBorder />}
            </IconButton>
          </Tooltip>
          <Typography variant="body2" color="text.secondary">
            {content.likeCount}
          </Typography>

          <Tooltip title="评论">
            <IconButton
              size="small"
              onClick={handleCommentClick}
              disabled={loading}
              sx={{
                color: 'text.secondary',
                '&:hover': {
                  color: 'primary.main',
                  backgroundColor: 'primary.50',
                },
              }}
            >
              <Comment />
            </IconButton>
          </Tooltip>
          <Typography variant="body2" color="text.secondary">
            {content.commentCount}
          </Typography>
        </Box>

        <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
          <Visibility sx={{ fontSize: 16, color: 'text.secondary' }} />
          <Typography variant="body2" color="text.secondary">
            {content.viewCount}
          </Typography>
        </Box>
      </CardActions>
    </Card>
  );
};

export default ContentCard; 